package com.heima.comment.service.impl;

import java.lang.reflect.AccessibleObject;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.comment.service.CommentRepayService;
import com.heima.feigns.ApUserFegin;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lo
 * @date 2021/10/3
 */
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    ApUserFegin apUserFegin;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 加载评论回复列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        // 1. 校验参数
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //2.获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();

        //3.获取回复列表
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(Query.query(Criteria
                .where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApCommentRepay.class);

        //4.查询回复点赞列表
        List<String> collect = apCommentRepays.stream().map(apCommentRepay -> apCommentRepay.getId()).collect(Collectors.toList());

        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria
                .where("authorId").is(userId)
                .and("commentRepayId").in(collect)), ApCommentRepayLike.class);

        List<ApCommentRepayVO> apCommentRepayVoS = new ArrayList<>();


        //5.封装数据
        if (CollectionUtils.isNotEmpty(apCommentRepays) && CollectionUtils.isNotEmpty(apCommentRepayLikes)) {
            apCommentRepays.forEach(apCommentRepay -> {
                ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
                BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
                //遍历点赞列表
                apCommentRepayLikes.forEach(apCommentRepayLike -> {
                    if (apCommentRepayLike.getCommentRepayId().equals(apCommentRepay.getId())) {
                        apCommentRepayVO.setOperation((short) 0);
                    }
                });
                apCommentRepayVoS.add(apCommentRepayVO);
            });
            return ResponseResult.okResult(apCommentRepayVoS);
        }

        return ResponseResult.okResult(apCommentRepays);
    }

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {

        //1.获取当前登录用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();
        //2.根据用户id查询用户
        ResponseResult<ApUser> result = apUserFegin.findUserById(userId);
        if (result.getCode() != 0 || result.getData() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        ApUser apUser = result.getData();

        //3.校验参数
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        return ResponseResult.okResult(apCommentRepay);
    }

    /**
     * 评论回复点赞
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1.获取当前登录用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();

        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        //2.判断是否是点赞
        if (dto.getOperation() == 0) {
            //不能重复点赞
            ApCommentRepayLike repayLike = mongoTemplate.findOne(Query.query(Criteria.
                    where("commentRepayId").is(dto.getCommentRepayId())
                    .and("authorId").is(userId)),ApCommentRepayLike.class);
            if (repayLike != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "不要重复点赞");
            }
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(userId);
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.save(apCommentRepayLike);

            //回复点赞的数量加一
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
        } else {
            //回复点赞数量减一
            apCommentRepay.setLikes(apCommentRepay.getLikes() > 0 ? apCommentRepay.getLikes() - 1 : 0);
            mongoTemplate.save(apCommentRepay);
            //删除点赞信息
            mongoTemplate.remove(Query.query(Criteria
                    .where("authorId").is(userId)
                    .and("commentRepayId").is(dto.getCommentRepayId())), ApCommentRepayLike.class);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
